package com.solution.admin.point.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.coupon.constants.CouponConstants.IsUsed;
import com.solution.admin.point.constants.PointConstants.PointOperateFlag;
import com.solution.admin.point.constants.PointConstants.PointOperateType;
import com.solution.admin.point.entity.PointMonthEntity;
import com.solution.admin.point.entity.PointMonthModifyEntity;
import com.solution.admin.point.service.PointMonthService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.constants.PublicStatus.SysCode;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils;

/**
 * 月度积分统计信息web控制层
 * 
 * @author xu_cc
 * @date 2017-10-20 14:21:47
 */
@RequestMapping("/pointMonth")
@Controller
public class PointMonthController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(PointMonthController.class);

	@Autowired
	private PointMonthService pointMonthService;
	

	/**
	 * 跳转月度积分统计信息查询页面
	 * 
	 * @param PointMonth
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-10-20 14:21:47
	 */
	@RequestMapping("/toListPointMonthPage")
	public String toListPointMonthPage(HttpServletRequest request, Model model) {
		return "point/pointMonth_list";
	}

	/**
	 * 分页查询月度积分统计信息列表
	 * 
	 * @param pointMonth
	 *            接收界面查询条件参数
	 * @param request
	 *            请求对象
	 * @return 返回对应的页面视图
	 * @author xu_cc
	 * @date 2017-10-20 14:21:47
	 */
	@RequestMapping("/listPointMonthPage")
	@ResponseBody
	public JSONGrid listPointMonthPage(PointMonthEntity pointMonth, HttpServletRequest request) {
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("customerName", pointMonth.getCustomerName());
		paramMap.put("companyName", pointMonth.getCompanyName());
		paramMap.put("mobile", pointMonth.getMobile());
		paramMap.put("month", pointMonth.getMonth());
		try {
			PageBean pageBean = pointMonthService.listPointMonthPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JSONGrid();
	}

	
	/**
	 * 查询月度积分订单状态
	 * @param request
	 * @return
	 */
	@RequestMapping("/listPointMonthConfirmStatus")
	@ResponseBody
	public Map<String, Object> listPointMonthConfirmStatus(HttpServletRequest request){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 1;
		PointMonthModifyEntity status;
		try {
			String month = request.getParameter("month");
			String currentMonth = DateUtils.getCurMonthYYYYMM();
			// 当月和大于当前月份不显示积分确认按钮
			if(DateUtils.getCurMonthYYYYMM().equals(month) || month.compareTo(currentMonth) > 0){
				result = 1;
			}else{
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("month", month);
				status = pointMonthService.selectPointMonthConfirmStatus(param);
				result = status == null ? 0 : 1;
			}
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("查询月度积分状态失败", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, "0");
			resultMap.put(PublicStatus.RESULT_MSG, "操作失败");
		}
		return resultMap;
	}
	
	
	/**
	 * 确认
	 * @param request
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年12月1日 下午4:42:28
	 */
	@RequestMapping("/doConfirmModify")
	@ResponseBody
	public BaseReturn doConfirmModify(HttpServletRequest request) {
		BaseReturn result = new BaseReturn();
		try {
			
			String month =request.getParameter("month");
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("month", month);
			param.put("confirmUser", getUserCode());
			int rows = pointMonthService.doConfirmMonthModify(param);
			if (rows == -1) {
				result.setCode(SysCode.FAILED);
				result.setMsg("没有需要确认的记录！");
			} else {
				result.setCode(SysCode.SUCCESS);
				result.setMsg("成功调整： " + rows + " 条！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("确认调整异常！");
		}
		return result;
	}

	/**
	 * 保存订单增加积分
	 * 
	 * @param monthModify
	 * @param request
	 * @return BaseReturn
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2017年11月30日 下午5:25:51
	 */
	@RequestMapping("/saveOrderPoint")
	@ResponseBody
	public BaseReturn saveOrderPoint(PointMonthModifyEntity monthModify, HttpServletRequest request) {
		BaseReturn result = new BaseReturn();
		try {
			if (null == monthModify || null == monthModify.getId() || null == monthModify.getOrderPoint()) {
				result.setCode(SysCode.FAILED);
				result.setMsg("保存失败，参数错误！");
				return result;
			}
			//目标积分
			BigDecimal actOrderPoint = monthModify.getOrderPoint();
			// 改的是哪一条
			PointMonthEntity pointMonth = pointMonthService.getPointMonthById(monthModify.getId());
			if (null != pointMonth) {
				// 系统计算的订单积分（原积分）
				BigDecimal systemOrderPoint = pointMonth.getOrderPoint();
				//将所有已调整过的积分拉出来
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("customerId", pointMonth.getCustomerId());
				param.put("month", pointMonth.getMonth());
				param.put("isUsed", IsUsed.USED);
				List<PointMonthModifyEntity> modifyList = pointMonthService.listMonthModifyList(param);
				// 计算现在调整过的订单积分是多少
				if (null != modifyList && modifyList.size() > 0) {
					for (PointMonthModifyEntity modify : modifyList) {
						if (modify.getOperateFlag().equals(PointOperateFlag.FLAG_ADD.getId())) {
							systemOrderPoint = systemOrderPoint.add(modify.getOperatePoint());
						} else if (modify.getOperateFlag().equals(PointOperateFlag.FLAG_MINUS.getId())) {
							systemOrderPoint = systemOrderPoint.subtract(modify.getOperatePoint());
						}
					}
				}
				// 人工于系统比较
				// 结果是:-1 小于,0 等于,1 大于
				BigDecimal optPoint = BigDecimal.ZERO;
				Integer optFlag = null;
				String operateType = null;
				if (actOrderPoint.compareTo(systemOrderPoint) == 1) {
					// 加（人工大于系统）
					optPoint = actOrderPoint.subtract(systemOrderPoint);
					optFlag = PointOperateFlag.FLAG_ADD.getId();
					operateType = PointOperateType.OPT_MONTH_ORDER_ADD.getCode();
				} else if (actOrderPoint.compareTo(systemOrderPoint) == -1) {
					// 减（人工小于系统）
					optPoint = systemOrderPoint.subtract(actOrderPoint);
					optFlag = PointOperateFlag.FLAG_MINUS.getId();
					operateType = PointOperateType.OPT_MONTH_ORDER_MINUS.getCode();
				} else {
					// do nothiong
					result.setCode(SysCode.FAILED);
					result.setMsg("无需修改！");
					return result;
				}
				// 赋值
				monthModify.setCustomerId(pointMonth.getCustomerId());
				monthModify.setMonth(pointMonth.getMonth());
				monthModify.setOperateFlag(optFlag);
				monthModify.setOperateType(operateType);
				monthModify.setOperatePoint(optPoint);
				monthModify.setIsUsed(IsUsed.UN_USED);
				monthModify.setCreater(getUserName());
				monthModify.setModifier(getUserName());
				pointMonthService.saveMonthModify(monthModify);
				result.setCode(SysCode.SUCCESS);
				result.setMsg("保存成功！");
			} else {
				result.setCode(SysCode.FAILED);
				result.setMsg("没有该客户的月度积分统计信息！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(SysCode.ERROR);
			result.setMsg("保存订单增加积分异常！");
		}
		return result;
	}

}
